
package com.hunhjy.core.kit;

import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.hunhjy.core.Const;

/**
 * 
 * @Description: property加载类
 * @author ZhuoQi_Zou
 * @date 2016年6月25日 下午11:12:52
 *
 */
public class PropKit extends PropertyPlaceholderConfigurer {

	private static Map<String, String> ctxPropertiesMap = new Hashtable<String, String>();

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		for (Object key : props.keySet()) {
			String keyStr = key.toString();
			String value = props.getProperty(keyStr);
			if (value == null) {
				value = "";
			}
			try {
				value = new String(value.getBytes(Const.ENCODE_ISO8859_1), Const.ENCODE_UTF_8);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			ctxPropertiesMap.put(keyStr, value);
		}

	}

	public static String get(String key) {
		return ctxPropertiesMap.get(key);
	}

	public static Integer getInt(String key) {
		return getInt(key, null);
	}

	public static Integer getInt(String key, Integer defaultValue) {
		String value = get(key);
		if (value != null)
			return Integer.parseInt(value.trim());
		return defaultValue;
	}

	public static Long getLong(String key) {
		return getLong(key, null);
	}

	public static Long getLong(String key, Long defaultValue) {
		String value = get(key);
		if (value != null)
			return Long.parseLong(value.trim());
		return defaultValue;
	}

	public static Boolean getBoolean(String key) {
		return getBoolean(key, null);
	}

	public static Boolean getBoolean(String key, Boolean defaultValue) {
		String value = get(key);
		if (value != null) {
			value = value.toLowerCase().trim();
			if ("true".equals(value))
				return true;
			else if ("false".equals(value))
				return false;
			throw new RuntimeException("The value can not parse to Boolean : " + value);
		}
		return defaultValue;
	}

}
